package com.tcr.action;

import java.util.Map;

import com.opensymphony.xwork2.Action;
import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.tcr.common.Constant;
import com.tcr.common.TcUser;
import com.tcr.dao.UserDao;
import com.tcr.util.HashUtil;

public class UserAction extends ActionSupport {

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;

	private String username;
	private String password;

	public String getUsername() {
		return username;
	}

	public void setUsername(String username) {
		this.username = username;
	}

	public void setPassword(String password) {
		this.password = password;
	}

	public String getPassword() {
		return password;
	}

	// login
	public String login() {
		String username = this.getUsername().trim();
		String password = this.getPassword().trim();
		// get md5
		String passmd5 = HashUtil.getMd5(password);

		if (username.equals(Constant.admin_name)
				&& passmd5.equals(Constant.admin_pass)) {
			session = ActionContext.getContext().getSession();
			session.put("isLogin", new Boolean(true));
			session.put("admin", new Integer(1));
			return "admin";
		}

		TcUser user = UserDao.getUser(username, passmd5);
		if (user == null) {
			addFieldError("err", "用户名和密码错误");
			return Action.LOGIN;
		} else {
			session = ActionContext.getContext().getSession();
			session.put("isLogin", new Boolean(true));
			session.put("admin", new Integer(0));
			session.put("user", user);
			this.setUser(user);
			return Action.SUCCESS;
		}
	}

	//
	public String logout() {
		session = ActionContext.getContext().getSession();
		session.put("isLogin", null);
		return Action.LOGIN;
	}

	public String home() {
		session = ActionContext.getContext().getSession();
		Boolean is_login = (Boolean) session.get("isLogin");
		Integer admin = (Integer) session.get("admin");

		if (!is_login.booleanValue())
			return Action.LOGIN;

		if (admin.intValue() == 1)
			return "admin";
		else
			return Action.SUCCESS;
	}

	public void setUser(TcUser user) {
		this.user = user;
	}

	public TcUser getUser() {
		return user;
	}

	private Map<String, Object> session;
	private TcUser user;
}
